#define _CRT_SECURE_NO_WARNINGS 1

#include <string>
using namespace std;
class Solution {
public:
    int myAtoi(string str) {
        int flag = 1;
        int count = 0;
        int first = 0;
        string numstr;
        for (const auto& e : str)
        {

            if (first == 1 && (e < '0' || e>'9'))
                break;
            if (count == 0 && e == '0')
                first = 1;
            if (e == '-')
            {
                flag = -1;
                first = 1;
                continue;
            }
            if (e == '+')
            {
                first = 1;
                continue;
            }

            if (e != ' ' && e != '-' && e != '+' && (e < '0' || e>'9'))
                break;
            if (e >= '0' && e <= ' 9')
            {
                if (e == '0' && count == 0)
                {

                }
                else
                {
                    numstr += e;
                    ++count;
                    first = 1;
                }
            }
            else if (count > 0)
                break;
        }
        long long dig = 1;
        long long ret = 0;
        if (count > 10)
        {
            if (flag == -1)
                return -2147483648;
            else
                return 2147483648 - 1;
        }
        for (int i = numstr.size() - 1; i >= (int)numstr.size() - count; --i)
        {
            if (ret + (numstr[i] - '0') * dig > 2147483648 - 1)
            {
                if (flag == -1 && ret + (numstr[i] - '0') * dig >= 2147483648)
                    return -2147483648;
                else
                    return 2147483648 - 1;
            }
            ret += (numstr[i] - '0') * dig;
            dig *= 10;
        }
        return ret * flag;
    }
};